package com.hm.PushCaseService.framework.service.crypto;


import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES对称加密
 * mode:ECB模式（只需要密钥，不需要偏移量）
 * 密钥(只能大小写字母+数字+长度最长32位)
 * 可以和前端：crypto-js 相互匹配
 */

@Service
public class CryptoService implements ICryptoService {

    //定义加密算法
    private static final String Algorithm = "AES/ECB/PKCS5Padding";

    @Override
    public String encrypt(String secretKey, String content) {
        try {
            Cipher cipher = Cipher.getInstance(Algorithm);
            //注意如果secretKey是动态的，这里不能写单例模式 必须每次要new
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            byte[] cipherBytes = cipher.doFinal(contentBytes);
            return Base64.getEncoder().encodeToString(cipherBytes);
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @Override
    public String decrypt(String secretKey, String content) {
        try {
            //base64密文解码
            byte[] encrypted = Base64.getDecoder().decode(content);
            Cipher cipher = Cipher.getInstance(Algorithm);
            //注意如果secretKey是动态的，这里不能写单例模式 必须每次要new
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptBytes = cipher.doFinal(encrypted);
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
